﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DosTexPrj.Core.Models;
using DosTexPrj.Core.RepositoriesInterface;
using DosTexPrj.Implement.NHibernate;
using DosTexPrj.UI.WinForm.Commons;

namespace DosTexPrj.UI.WinForm
{
    public partial class DeliveryDetailForm : Form
    {
        #region --- Private members ---

        private IRepository _repository;
        private Order _currentOrder;
        private double _inputKgQuantity;
        private double _inputMtQuantity;
        private double _currentKgQuantity;
        private double _currentMtQuantity;
        private double _KgQuantityDeliveried;
        private double _MtQuantityDeliveried;

        #endregion --- Private members ---

        #region --- Properties ---

        public Order CurrentOrder
        {
            get { return this._currentOrder; }
            set { this._currentOrder = value; }
        }

        public List<DeliveryDetail> DeliveryDetailsFromDeliveryForm { get; set; }

        #endregion --- Properties ---

        #region --- Constructors ---

        public DeliveryDetailForm()
        {
            InitializeComponent();
            _repository = MyServiceLocator.DoGetInstance<IRepository>();
            this.DeliveryDetailsFromDeliveryForm = new List<DeliveryDetail>();
            this.txtQttKg.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtQttMt.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtQttMt.MaxLength = this.txtQttKg.MaxLength = 12;
        }

        #endregion --- Constructors ---

        private void DeliveryDetailForm_Load(object sender, EventArgs e)
        {
            // Clear form and load comboboxes
            ClearForm();
        }

        private void Textbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            Common.HandlingNumberTextbox(e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValidate())
            {
                return;
            }
            var CurrentDeliveryDetail = new DeliveryDetail();
            CurrentDeliveryDetail.ReferenceToOrderDetail = (OrderDetail)cboOrderDetail.SelectedItem;

            double qttKg = 0;
            double.TryParse(txtQttKg.Text.Trim(), out qttKg);

            double qttMt = 0;
            double.TryParse(txtQttMt.Text.Trim(), out qttMt);

            var tempKgQuantity = this._KgQuantityDeliveried + qttKg;
            var tempMtQuantity = this._MtQuantityDeliveried + qttMt;
            if (tempKgQuantity > this._currentKgQuantity || tempMtQuantity > this._currentMtQuantity)
            {
                MessageBox.Show("value is greater than remaining");
                return;
            }

            CurrentDeliveryDetail.KgQuantity = qttKg;
            CurrentDeliveryDetail.MtQuantity = qttMt;
            var temp = (from detail in this.DeliveryDetailsFromDeliveryForm
                        where detail.Id == Guid.Empty && detail.ReferenceToOrderDetail.Id == CurrentDeliveryDetail.ReferenceToOrderDetail.Id
                        select detail).SingleOrDefault();
            this.DeliveryDetailsFromDeliveryForm.Remove(temp);
            this.DeliveryDetailsFromDeliveryForm.Add(CurrentDeliveryDetail);
            this.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void cboOrderDetail_SelectedIndexChanged(object sender, EventArgs e)
        {
            OrderDetail orderDetail = (OrderDetail)cboOrderDetail.SelectedItem;
            cboComposition.SelectedValue = orderDetail.Composition.Id;
            cboFabricType.SelectedValue = orderDetail.FabricType.Id;
            txtColor.Text = orderDetail.Color;
            txtCuttableWidth.Text = orderDetail.CuttableWidth.ToString();
            txtWeight.Text = orderDetail.Weight.ToString();
            //tracking current quantities
            this._currentKgQuantity = orderDetail.KgQuantity;
            this._currentMtQuantity = orderDetail.MtQuantity;
            //tracking quantities was deliveried
            this.CalculateQuantityDeliveried(orderDetail);
        }

        #region Functions

        private void CalculateQuantityDeliveried(OrderDetail orderDetail)
        {
            this._KgQuantityDeliveried = 0;
            this._MtQuantityDeliveried = 0;
            if (this.DeliveryDetailsFromDeliveryForm == null || this.DeliveryDetailsFromDeliveryForm.Count == 0)
            {
                return;
            }
            var temp = (from deliveryDetail in this.DeliveryDetailsFromDeliveryForm
                        where deliveryDetail.Id != Guid.Empty && deliveryDetail.ReferenceToOrderDetail.Id == orderDetail.Id
                        select deliveryDetail).ToList();
            this._KgQuantityDeliveried = temp.Sum(x => x.KgQuantity);
            this._MtQuantityDeliveried = temp.Sum(x => x.MtQuantity);
        }

        private void LoadFabricType()
        {
            try
            {
                var fabricData = _repository.GetAll<FabricType>();
                IList<FabricType> fabrics = new List<FabricType>();

                fabrics = (from f in fabricData
                           select new FabricType
                               {
                                   Id = f.Id,
                                   FabricTypeName = f.FabricTypeName
                               }).ToList();

                if (fabrics.Count > 0)
                {
                    cboFabricType.DataSource = fabrics;
                    cboFabricType.DisplayMember = "FabricTypeName";
                    cboFabricType.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadComposition()
        {
            try
            {
                var compositionData = _repository.GetAll<Composition>();
                IList<Composition> compositions = new List<Composition>();

                compositions = (from c in compositionData
                                select new Composition
                                {
                                    Id = c.Id,
                                    CompostionName = c.CompostionName
                                }).ToList();

                if (compositions.Count > 0)
                {
                    cboComposition.DataSource = compositions;
                    cboComposition.DisplayMember = "CompostionName";
                    cboComposition.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadOrderDetail()
        {
            try
            {
                if (this.CurrentOrder != null)
                {
                    var orderDetailData = _repository.GetAll<OrderDetail>().Where(x => x.Order.Id == this.CurrentOrder.Id);
                    IList<OrderDetail> orderDetails = new List<OrderDetail>();

                    orderDetails = (from c in orderDetailData
                                    select new OrderDetail
                                    {
                                        Id = c.Id,
                                        Color = c.Color,
                                        Composition = c.Composition,
                                        CuttableWidth = c.CuttableWidth,
                                        FabricType = c.FabricType,
                                        IsDone = c.IsDone,
                                        KgQuantity = c.KgQuantity,
                                        MtQuantity = c.MtQuantity,
                                        Order = c.Order,
                                        Price = c.Price,
                                        Weight = c.Weight
                                    }).ToList();

                    if (orderDetails.Count > 0)
                    {
                        cboOrderDetail.DataSource = orderDetails;
                        cboOrderDetail.DisplayMember = "Id";
                        cboOrderDetail.ValueMember = "Id";
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void ClearForm()
        {
            // Clear textboxes
            txtColor.Text = string.Empty;
            txtQttKg.Text = string.Empty;
            txtQttMt.Text = string.Empty;
            txtCuttableWidth.Text = string.Empty;
            txtWeight.Text = string.Empty;
            // Disable controls
            txtColor.Enabled = txtCuttableWidth.Enabled = txtWeight.Enabled = cboComposition.Enabled = cboFabricType.Enabled = false;
            // Load comboboxes
            LoadOrderDetail();
            LoadFabricType();
            LoadComposition();
        }

        private bool CheckValidate()
        {
            error.Clear();
            bool flag = true;
            if (!Common.IsBlankTextBox(txtQttKg, "Required field!", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtQttMt, "Required field!", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboOrderDetail, "Required Field", error))
                flag = false;
            return flag;
        }

        #endregion Functions
    }
}